<template>
<div class="tree-block content">
  <Input search v-model="searchWord" @on-search="searchTree(searchWord,data2)" @on-enter='searchTree(searchWord,data2)' />
   <div class="demo-spin-container mt10" v-show="loading" > <Spin fix></Spin></div>
  <Tree v-show="!loading" class="mt10 w-72" ref="tree"   expand-node @on-check-change="checkchange"  :data="data2" show-checkbox ></Tree>
</div>
</template>

<script>
import tool from "@/libs/tool";
import {orgTree} from "../../api/base";

export default {
  data () {
    return {
      data2:[],
      searchWord:'',
      loading:false
    }
  },
 async created() {

  },
  async mounted() {
    this.loading=true;
    await this.getOrgTree();
    this.loading=false;

    },
  methods:{
      searchTree(value, arr){
        if (!value) { //内容为空时，查询所有
          this.getOrgTree()
        }
        const rebuildData=(value, arr) => {
          let newarr = [];
          arr.forEach(element => {
            if (element.children && element.children.length) {
              if (element.title.indexOf(value) > -1) {
                element.expand = true;
                newarr.push(element);
              }
              const ab = rebuildData(value,element.children);
              const obj = {
                ...element,
                expand: true,
                children: ab
              };
              if (ab && ab.length) {
                newarr.push(obj);
              }
            } else {
              if (element.title.indexOf(value) > -1) {
                newarr.push(element);
              }
            }
          });
          return newarr;
        };
        this.data2 = [];
        this.changeData(rebuildData(value, arr))
      },
    checkchange(arr){
      // console.log(arr,'========');
      this.sendData(arr);
    },
    sendData(arr,value){
      let ids=arr.map(item=>{return item.id}).join();
      this.$store.commit('admin/base/changeData',{name:'orgIds',value:ids})
    },
    async getOrgTree() {
      this.$store.commit('admin/base/changeData',{name:'orgIds',value:''})
      let res=await orgTree({});
      this.changeData(_.get(res,'data')||[])

    },
    changeData(arr){
      this.data2 =tool.formatTree(arr,'children','lable');
      this.$nextTick(()=>{
        let arr= this.$refs.tree.getCheckedNodes();
        this.sendData(arr)
      })
    }
  },
}
</script>

<style  lang="less" scoped>
/deep/.demo-spin-container{
  display:block;
  height: 100px;
  position: relative;
  .ivu-spin-fix{
    background: none !important;
  }
}

</style>
